package com.tth.learn.addproperties.java;

import org.junit.Test;

import java.io.*;

/**
 * @Author tth
 * @Date 2022/12/26 15:06
 */
public class InputStreamReaderOutputStreamWriter {

    /**
     * 借助InputStreamReader和OutputStreamWriter，将utf-8格式的文本文件复制为gbk格式的文件
     */
    @Test
    public void test() {
        InputStreamReader isr = null;
        OutputStreamWriter osw = null;
        try {
            // 1.造流
            FileInputStream fis = new FileInputStream("hello.txt");
            FileOutputStream fos = new FileOutputStream("hello_gbk.txt");

            isr = new InputStreamReader(fis, "utf-8");
            osw = new OutputStreamWriter(fos, "gbk");

            // 2.复制
            char[] cbuf = new char[10];
            int len;
            while ((len = isr.read(cbuf)) != -1) {
                osw.write(cbuf);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 3.关闭流
            if (null != isr) {
                try {
                    isr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (null != osw) {
                try {
                    osw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
